package com.fufu.mq;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

/**
 * 生产者
 */
public class Producer {

    public static void main(String[] args) throws Exception {

        String exchangeName = "my-first-exchange";
        String queueName = "my-first-queue";

        // 创建一个连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        // 服务地址
        factory.setHost("localhost");
        // 端口号
        factory.setPort(5672);
        // 用户名
        factory.setUsername("guest");
        // 密码
        factory.setPassword("guest");

        // 新建连接
        Connection connection = factory.newConnection();
        // 创建信道
        Channel channel = connection.createChannel();
        // 连接交换机
        channel.exchangeDeclare(exchangeName, BuiltinExchangeType.DIRECT,true,false,null);

        // 连接队列
        channel.queueDeclare(queueName,true,false,false,null);

        // 路由key
        String routingKey = "my-first-queue";
        // 交换机和队列绑定
        channel.queueBind(queueName,exchangeName,routingKey);

        String message = "Hello World!";
        // 发送消息
        channel.basicPublish(exchangeName,routingKey,null,message.getBytes());

        System.out.println("消息已发送");
        channel.close();
        connection.close();
    }
}
